#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "libfdr/jrb.h"
#include "ec.h"
#define K 4
#define M 2
#define W 8
#define CANARY_SIZE 16

int put(char *filename)
{
  /*char *servers[] = {"hydra1.eecs.utk.edu", "hydra2.eecs.utk.edu",
                     "hydra3.eecs.utk.edu", "hydra4.eecs.utk.edu",
                     "hydra5.eecs.utk.edu", "hydra6.eecs.utk.edu"};
  */
  char *servers[6];
  char *data, *temp;
  char buf[1000];
  unsigned long size, pad=0, block_size;
  int i, j, pool_size;
  FILE *file;
  char **data_ptrs, **code_ptrs;
  JRB server_pool = make_jrb();
  JRB jtemp;

  //read all the servers from the servers.txt
  file = fopen("servers.txt", "r");
  if(file == NULL)
  {
    perror("servers.txt");
    return 1;
  }

  pool_size=0;
  while(fgets(buf, 1000, file) != NULL)
  {
    if(buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = '\0';
    jrb_insert_int(server_pool, pool_size, new_jval_s(strdup(buf)));
    pool_size++;
  }
  fclose(file);

  if(pool_size < 6)
  {
    fprintf(stderr, "Must have at least 6 servers listed in servers.txt\n");
    return 1;
  }

  //now randomly choose 6 of those servers
  srand(time(NULL));
  for(i=0; i < 6; i++)
  {
    jtemp = jrb_find_gte_int(server_pool, rand() % pool_size, &j);
    servers[i] = jtemp->val.s;
    pool_size--;
    jrb_delete_node(jtemp);
  }

  file = fopen(filename, "r");
  if(file == NULL)
  {
    perror(filename);
    return 1;
  }

  //determine size
  fseek(file, 0, SEEK_END);
  size = ftell(file);

  //pad the buffer so that the 4 chunks will be long aligned
  if(size % (sizeof(long)*K) != 0)
    pad = (sizeof(long)*K) - (size % (sizeof(long)*K));
  data = malloc(size+pad+CANARY_SIZE);
  block_size = (size+pad+CANARY_SIZE) / K;

  //read file
  rewind(file);
  fread(data, 1, size, file);
  fclose(file);

  encrypt(data, size+pad);

  data_ptrs = malloc(sizeof(char *) * K);
  //code_ptrs = malloc(sizeof(char *) * M);

  for(i=0; i < K; i++)
    data_ptrs[i] = data + block_size*i;

  code_ptrs = encode(data, block_size, data_ptrs);
  
  //i need to get an actual server name into these function calls
  //temporarily using premade array indexed into with j

  printf("%lu\n%lu\n", block_size, pad);
  for(i=0, j=0; i < K; i++, j++)
  {
    temp = upload(data_ptrs[i], block_size, servers[j]);
    printf("%s %s\n", servers[j], temp);
  }
  for(i=0; i < M; i++, j++)
  {
    temp = upload(code_ptrs[i], block_size, servers[j]);
    printf("%s %s\n", servers[j], temp);
  }
}
